package com.qymerge.manage.core.controller;

import com.qymerge.manage.core.enums.ErrorCodeTypes;
import com.qymerge.manage.core.utils.PrintCodeUtils;
import com.google.gson.JsonSyntaxException;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Desc
 * User cong.li
 * Date 2017/4/4
 * Time 20:59
 */
@Controller
@RequestMapping(value = "/")
public class BaseController {

    static Logger logger = LogManager.getLogger(BaseController.class);

    /**
     * 异常拦截器
     *
     * @param request
     * @param response
     * @param ex
     * @throws IOException
     */
    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        String callback = request.getParameter("callback");
        String lm = "";
        if (ex != null) {
            lm = ex.getMessage();
            ex.printStackTrace();
        }
        lm = lm != null ? lm.replace("\"", "") : "服务器响应异常";
        if (ex instanceof HttpMediaTypeException) {
            PrintCodeUtils.printError(response, ErrorCodeTypes.MethodNotSupport.getName(), callback);
            logger.error(ErrorCodeTypes.MethodNotSupport.getName());
        } else if (ex instanceof HttpMessageNotReadableException) {
            PrintCodeUtils.printError(response, ErrorCodeTypes.CoundNotReadJson.getName(), callback);
            logger.error(ErrorCodeTypes.CoundNotReadJson.getName());
        } else if (ex instanceof JsonSyntaxException) {
            PrintCodeUtils.printError(response, ErrorCodeTypes.CoundNotReadJson.getName(), callback);
            logger.error(ErrorCodeTypes.CoundNotReadJson.getName());
        } else {
            PrintCodeUtils.printError(response, lm, callback);
            logger.error(ex.toString() + "-" + ex.getMessage());
        }
    }

}
